<template>
  <n-spin :show="inLoading" class="w-full h-full">
    <div id="relationChart" class="w-full h-96"></div>
  </n-spin>
</template>

<script setup>
import * as echarts from 'echarts'

const props = defineProps(['data'])
const router = useRouter()

onMounted(() => {
  init()
})

const chartDom = ref(null)
const myChart = ref(null)

const inLoading = ref(false)

const option = {
  tooltip: {
    formatter: (item) => {
      if (item.dataType === 'node') {
        return `<strong>${item.data.name}</strong><br />研究成果：${item.data.value}`
      } else if (item.dataType === 'edge') {
        if (item.data.type === 'following') {
          return '关注'
        } else {
          return '同机构成员'
        }
      }
    }
  },
  series: [
    {
      type: 'graph',
      layout: 'none',
      data: [],
      links: [],
      roam: true,
      categories: [
        {
          name: 'Expert'
        }
      ],
      labelLayout: {
        hideOverlap: true
      },
      itemStyle: {
        color: '#ffa157'
      },
      lineStyle: {
        color: 'source',
        curveness: 0.3
      },
      emphasis: {
        lineStyle: {
          width: 10
        }
      },
      scaleLimit: {
        min: 0.4,
        max: 2
      }
    }
  ]
}

watch(
  () => props.data,
  () => {
    refresh()
  }
)

const init = () => {
  inLoading.value = true
}

const refresh = () => {
  if (!chartDom.value && !myChart.value) {
    const targetDOM = document.getElementById('relationChart')
    targetDOM.removeAttribute('_echarts_instance_')
    chartDom.value = targetDOM
    myChart.value = echarts.init(chartDom.value)
  }
  if (props.data) {
    inLoading.value = true
    option.series[0].data = props.data.nodes
    option.series[0].links = props.data.links
    inLoading.value = false
    myChart.value.setOption(option)
    myChart.value.on('click', (param) => {
      router.push({ name: 'Profile', params: { id: param.data.id } })
    })
  }
}
</script>

<style scoped></style>
